<template>
  <div class="flex gap-2">
    <el-tag
      v-for="tag in dynamicTags"
      :type="tagType"
      :key="tag"
      :disable-transitions="false"
      round
      v-bind="$attrs"
    >
      {{ tag }}
    </el-tag>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, onMounted, watch } from "vue";

const props = defineProps({
  dynamicTags: {
    type: String,
    default: () => ["Tag 1", "Tag 2", "Tag 3"],
  },
  // Tag 的类型
  tagType: {
    type: String,
    default: () => "primary",
  },
});

// 标签数组
const dynamicTags = ref<string[]>([]);

// 初始化 dynamicTags
onMounted(() => {
  // 将json字符串转为数组，添加空值检查
  try {
    dynamicTags.value = JSON.parse(props.dynamicTags || "[]");
  } catch (error) {
    console.error("Invalid JSON string for dynamicTags:", props.dynamicTags);
    dynamicTags.value = [];
  }
});

// 在onMounted生命周期后添加数据监听
watch(
  () => props.dynamicTags,
  (newVal) => {
    try {
      dynamicTags.value = JSON.parse(newVal || "[]");
    } catch (e) {
      dynamicTags.value = [];
    }
  },
  { deep: true, immediate: true }
);
</script>
